package com.csun.dsms.utils.pt;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.model.huang.HgInstructionListData;
import com.csun.dsms.model.huang.HgOaLoginData;
import com.csun.dsms.utils.DateUtil;
import com.csun.dsms.utils.MD5;
import com.csun.dsms.utils.aes.AESUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

@Slf4j
public class OAUtils {

//    http://36.133.17.156:18090/%23/dashboard/workplace
    private static final String BASEURL = "http://36.137.195.32:8888/cas/p3/serviceValidate?service=http://36.133.17.156:18090/%23/dashboard/workplace/&ticket=ST-6-P1MmCQKA-iWV-jrvlo-nWTmHTKU-service-cas-cfd88ccdf-x6l8c&format=JSON";
    private static final String APIKEY = "1830ee2c-3be2-4a23-b725-c16b12097203";

    public static String login(String ticket){
        String url = "http://36.137.195.32:8888/cas/p3/serviceValidate?service=http://36.133.17.156:18090/&ticket="+ticket+"&format=JSON";
//        String url = "http://36.137.192.6:8888/cas/p3/serviceValidate?service=http://36.133.17.156:18090/%23/dashboard/workplace/&ticket="+ticket+"&format=JSON";
        log.info(url);
        String result = OAPtReqUtil.httpGetRequest(url);
        log.info(result);
//        {
//            "serviceResponse": {
//            "authenticationSuccess": {
//                "user": "test1@939a6c08caec11e986998c1645557fc8",
//                        "attributes": {
//                    "tenementId": ["939a6c08caec11e986998c1645557fc8"],
//                    "isFromNewLogin": [false],
//                    "authenticationDate": [1742267328.245000000],
//                    "roleId": ["e30d31290e494090a67f186ce52b0932"],
//                    "successfulAuthenticationHandlers": ["QueryDatabaseAuthenticationHandler"],
//                    "mobile": ["13832190817"],
//                    "availableFlag": ["true"],
//                    "userName": ["测试1"],
//                    "userId": ["939b407a2b2f4b64aef4f40b1e55304b"],
//                    "orgId": ["02ddc2d1fd844316aa104d17289372ae"],
//                    "imId": ["1000301"],
//                    "credentialType": ["UsernamePasswordCredential"],
//                    "authenticationMethod": ["QueryDatabaseAuthenticationHandler"],
//                    "userAccount": ["test1"],
//                    "longTermAuthenticationRequestTokenUsed": [false],
//                    "position": [""],
//                    "email": ["test1@hgoa.com"],
//                    "statusFlag": ["true"]
//                }
//            }
//            }
//        }
        if (result!=null){
            HgOaLoginData hgOaLoginData = JSONObject.parseObject(result, HgOaLoginData.class);
            if (hgOaLoginData!=null && hgOaLoginData.getServiceResponse()!=null &&
                    hgOaLoginData.getServiceResponse().getAuthenticationSuccess()!=null){

                HgOaLoginData.AuthenticationSuccess authenticationSuccess =
                        hgOaLoginData.getServiceResponse().getAuthenticationSuccess();
                if (authenticationSuccess.getAttributes().getMobile()!=null &&
                    authenticationSuccess.getAttributes().getMobile().size()>0){
                    return authenticationSuccess.getAttributes().getMobile().get(0);
                }
//                String mobile = authenticationSuccess.getAttributes().getMobile().get(0);
//                String userId = authenticationSuccess.getAttributes().getUserId().get(0);
            }
        }
        return null;
    }

    public static String login2(String ticket){
        String url = "http://36.137.192.6:8888/cas/p3/serviceValidate?service=http://36.133.17.156:18090/&ticket="+ticket+"&format=JSON";
        log.info(url);
        String result = OAPtReqUtil.httpGetRequest(url);
        log.info(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject!=null && jsonObject.getString("data")!=null){
            String data = jsonObject.getString("data");
            try {
                return data;
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        return result;
    }

    public static String syncUser(){
        //hgcityCore/home/floatWindowUser
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phoneNum","16602722600");
        jsonObject.put("userName","fengzhiqi");
        jsonArray.add(jsonObject);
        System.out.println(jsonArray);
        String postJson = jsonArray.toJSONString();
        String key = "y8JiwSDcp09JKvr7";
        String iv = "0102030405060711";
        try {
            postJson = AESUtil.encryptAES(postJson, key, iv);
            System.out.println("data: " + postJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = "http://hgcity-dev.chutianyun.gov.cn:8016/hgapp-core/hgcityCore/home/floatWindowUser";
        String result = HuangGangPtReqUtil.httpJson(url,postJson);
        System.out.println("result: " + result);


        return postJson;
    }

    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 新增待办事项
     * @return
     */
    public static String sendTodo(HgInstructionListData hgInstructionListData, String oaId){
        String appId = "fef4d81a922d40f5bc0b3c16ad73cca8";
        String secret = "B37319C8E8BF13027A2B34FA774CE1EH";
        Long time = new Date().getTime();
        String appSecret = MD5.getMd5().getMD5ofStr(secret + time).toString();
        JSONObject jsonObject = new JSONObject();
        JSONObject headObj = new JSONObject();
        headObj.put("requestId","C80CBDE982F00001292F129F11A"+generateRandomString(5));
        headObj.put("timeStamp", time);
        headObj.put("appId",appId);
        headObj.put("appSecret",appSecret);
        JSONObject bodyObj = new JSONObject();
        bodyObj.put("appId",appId);
        bodyObj.put("receiverId",oaId);
        bodyObj.put("flowId","43413ff2e4e14f2ab9474970"+generateRandomString(8));
        bodyObj.put("flowType",2);
        bodyObj.put("flowTitle",hgInstructionListData.getApprover()+"领导批示,请点击查看");
        bodyObj.put("flowStatus",1);
        bodyObj.put("startTime", DateUtil.getNowTime());
        bodyObj.put("flowWebUrl","http://36.133.17.156:18090/");
        bodyObj.put("flowAppUrl","http://36.133.17.156:18090/phone");
        jsonObject.put("header",headObj);
        jsonObject.put("body",bodyObj);
        log.info(jsonObject.toJSONString());
        String url = "http://36.137.195.32:8888/uip/foreign/todo/add";
        log.info(url);
        String result = OAPtReqUtil.httpJson(url,jsonObject.toJSONString());
        log.info(result);
        return result;
    }


    public static void main(String[] args) {
//        String result = login("BH9ySLFaVp9T/mqow/w+p3mTBbhY5QcrP2mC7CVB5D3ez8nJ3gkYHRYj576PWL1afVqNAxfTueWNlSVmDF/hQDUwk27+vrSfnc99OyC5B805skeApJou5HchSPYsuEN+zOS5kOY4SFsdivJSoRQgGA==");
//        System.out.println(result);
        String result = syncUser();

        System.out.println(result);
    }

}
